<script lang="ts" setup>
import type { VbenFormProps, VxeGridListeners, VxeGridProps } from "#/adapter";

import { ref } from "vue";

import { Page } from "@vben/common-ui";

import { DownOutlined } from "@ant-design/icons-vue";
import { Button, message } from "ant-design-vue";

import { useVbenVxeGrid } from "#/adapter";
import { list, destroy, downloadById } from "#/api/system/files";
import { TableAction } from "#/components/table-action";
import { gridSchemas, searchFormSchemas } from "./schemas";


const hasTopTableDropDownActions = ref(false);
const postFormRef = ref();
const detailFormRef = ref();
const formOptions: VbenFormProps = {
  ...searchFormSchemas,
  collapsed: true,
  wrapperClass: "grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",
};

const gridOptions: VxeGridProps<any> = {
  ...gridSchemas,
  toolbarConfig: {
    ...gridSchemas.toolbarConfig,
    slots: {
      buttons: "toolbar-buttons",
    },
    custom: {
      // 自定义列-图标
      icon: "vxe-icon-menu",
    },
  },
  height: "auto",
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        return await list({
          page: page.currentPage,
          limit: page.pageSize,
          ...formValues,
        });
      },
    },
  },
};
const gridEvents: VxeGridListeners<any> = {
  checkboxChange() {
    // eslint-disable-next-line no-use-before-define
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
  checkboxAll() {
    // eslint-disable-next-line no-use-before-define
    const records = gridApi.grid.getCheckboxRecords();
    hasTopTableDropDownActions.value = records.length > 0;
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents,
});

// 下载
const handleDownload = (record: any) => {
  downloadById(record.id)
    .then((result) => {
      const blob = new Blob([result]); // 确保 result 是 Blob 数据
      const blobURL = window.URL.createObjectURL(blob);
      const tempLink = document.createElement("a");
      tempLink.style.display = "none";
      tempLink.href = blobURL;
      // 从 record 中获取文件名，提供一个默认值
      const filename = record.filename || "downloaded-file";
      tempLink.setAttribute("download", filename);
      document.body.appendChild(tempLink);
      tempLink.click();
      tempLink.remove();
      window.URL.revokeObjectURL(blobURL);
    })
    .catch((err) => {
      console.error("下载失败:", err);
    });
};

// 删除
const handleDelete = (row: any) => {
  let ids = [];
  if (row) {
    ids.push(row.id);
  } else {
    ids = gridApi.grid.getCheckboxRecords().map((item) => item.id);
  }
  destroy(0, { data: ids ?? [] }).then(() => {
    message.success("删除成功");
    gridApi.reload();
  });
};
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-buttons>
        <TableAction
          :actions="[]"
          :drop-down-actions="[
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              ifShow: hasTopTableDropDownActions,
              auth: ['admin', 'system:files:remove'],
              popConfirm: {
                title: '确定删除吗？',
                confirm: handleDelete.bind(null, false),
              },
            },
          ]"
        >
          <template #more>
            <Button style="margin-left: 8px">
              批量操作
              <DownOutlined />
            </Button>
          </template>
        </TableAction>
      </template>
      <template #toolbar-tools></template>
      <template #ACTION="{ row }">
        <TableAction
          :actions="[
            {
              label: '下载',
              type: 'link',
              size: 'small',
              auth: ['admin', 'system:files:download'],
              onClick: handleDownload.bind(null, row),
            },
            {
              label: '删除',
              type: 'link',
              size: 'small',
              auth: ['admin', 'system:files:remove'],
              popConfirm: {
                title: '确定删除吗？',
                confirm: handleDelete.bind(null, false),
              },
            },
          ]"
          :drop-down-actions="[]"
        />
      </template>
    </Grid>
  </Page>
</template>
